package com.yanjiali.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yanjiali.entity.Comment;
import com.yanjiali.model.R;
import com.yanjiali.model.req.CommentLikesReq;
import com.yanjiali.model.resp.CommentLikesResp;
import com.yanjiali.service.CommentService;
import com.yanjiali.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanjiali.entity.CommentLike;
import com.yanjiali.mapper.CommentLikeMapper;
import com.yanjiali.service.CommentLikeService;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Package: com.yanjiali.service.impl
 * @Author: yanjiali
 * @Created: 2025/4/23 21:33
*/
@Service
public class CommentLikeServiceImpl extends ServiceImpl<CommentLikeMapper, CommentLike> implements CommentLikeService{

//    @Autowired
//    private RedisUtil redisUtil;

    @Autowired
    private CommentService commentService;

//    @Override
//    public int getLikeCount(Long commentId) {
//        String COMMENT_LIKE_COUNT = getCommentLikeCountKey(commentId);
//        Integer count = redisUtil.get(COMMENT_LIKE_COUNT, Integer.class);
//        return count == null ? 0 : count;
//    }

    //TODO 简化版本
    @Override
    @Transactional
    public R<CommentLikesResp> liked(CommentLikesReq commentLikesReq) {
        //获取当前登录的用户id
        String userId = "";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null) {
            userId = authentication.getPrincipal().toString();
        }else {
            return R.fail("当前用户没有登录，无法点赞");
        }

        Long commentId = commentLikesReq.getCommentId();

        //构造对应条件构造器
        LambdaQueryWrapper<CommentLike> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(CommentLike::getCommentId, commentId)
                .eq(CommentLike::getUid, userId);

        LambdaUpdateWrapper<Comment> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        //查询
        CommentLike commentLike = getOne(lambdaQueryWrapper);

        if (commentLike != null) {  //表示点赞过了
            boolean remove = remove(lambdaQueryWrapper);
            if(!remove) {
                throw new RuntimeException("取消点赞失败");
            }

            //构造修改条件构造器，减少对应评论的点赞数量
            lambdaUpdateWrapper
                    .eq(Comment::getId, commentId)
                    .setSql("likes = likes - 1");
            boolean update = commentService.update(lambdaUpdateWrapper);
            if(!update) {
                throw new RuntimeException("减少点赞数量失败");
            }
            return R.ok(new CommentLikesResp("取消点赞"));
        }else { //没有点赞过
            commentLike = new CommentLike();
            commentLike.setCommentId(commentId);
            commentLike.setUid(Long.valueOf(userId));
            boolean save = save(commentLike);

            if(!save) {
                throw new RuntimeException("添加一条新的点赞记录失败");
            }

            //构造修改条件构造器，增加对应评论的点赞数量
            lambdaUpdateWrapper
                    .eq(Comment::getId, commentId)
                    .setSql("likes = likes + 1");
            boolean update = commentService.update(lambdaUpdateWrapper);
            if(!update) {
                throw new RuntimeException("增加点赞数量失败");
            }

            return R.ok(new CommentLikesResp("点赞成功"));
        }
    }

    //TODO 非简化版本，后续补充
//    @Override
//    public R<CommentLikesResp> liked(CommentLikesReq commentLikesReq) {
//        //获取当前登录的用户id
//        String userId = "";
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        if(authentication != null) {
//            userId = authentication.getPrincipal().toString();
//        }
//
//        //获取redis的键
//        String COMMENT_LIKE = getCommentLikeKey(userId);
//        String COMMENT_LIKE_COUNT = getCommentLikeCountKey(commentLikesReq.getCommentId());
//
//        // 查询用户是否点赞 int 2: mysql点赞 1: redis点赞 0: 不点赞
//        int state = this.isLiked(commentLikesReq);
//        switch (state) {
//            case 2:
//                // mysql取消点赞
//                redisUtil.execute(e -> {
//                    e.sSet(COMMENT_LIKE, -commentLikesReq.getCommentId());
//                    e.incr(COMMENT_LIKE_COUNT, -1);
//                });
//                break;
//            case 1:
//                // redis取消点赞
//                redisUtil.execute(e -> {
//                    e.sRemove(COMMENT_LIKE, commentLikesReq.getCommentId());
//                    e.incr(COMMENT_LIKE_COUNT, -1);
//                });
//                break;
//            case 0:
//                // redis点赞
//                redisUtil.execute(e -> {
//                    e.sSet(COMMENT_LIKE, commentLikesReq.getCommentId());
//                    e.incr(COMMENT_LIKE_COUNT, 1);
//                });
//                break;
//        }
//        return R.ok(new CommentLikesResp(true));
//    }

//    @Override
//    public int isLiked(CommentLikesReq commentLikesReq) {
//        // 用户id
//        String userId = "";
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        if(authentication != null) {
//            userId = authentication.getPrincipal().toString();
//        }
//
//        if("".equals(userId)) {
//            throw new RuntimeException("没有登录用户信息，却访问了需要登录才能调用的接口");
//        }
//
//        String COMMENT_LIKE = getCommentLikeKey(userId);
//
//        // 查询redis中是否点赞
//        Boolean state = redisUtil.sHasKey(COMMENT_LIKE, commentLikesReq.getCommentId());
//        if (state) {
//            return 1;
//        } else {
//            // redis中没有点赞，查询redis是否取消点赞
//            boolean cancel = redisUtil.sHasKey(COMMENT_LIKE, -commentLikesReq.getCommentId());
//            // 如果没取消点赞，查询mysql是否点赞
//            if (!cancel) {
//                CommentLike commentLike = this.getByCommentLikesReq(commentLikesReq);
//                // commentLike不等于null，mysql点赞了
//                return commentLike != null ? 2 : 0;
//            }
//        }
//        return 0;
//    }
//
//    /**
//     * 获取评论点赞redis中的：key
//     * @param uid 用户id
//     * @return
//     */
//    public String getCommentLikeKey(String uid) {
//        return String.format("comment-like:%d:comment-id", uid);
//    }
//
//    /**
//     * 获取评论点赞数量redis中的：key
//     * @param commentId 评论id
//     * @return
//     */
//    public String getCommentLikeCountKey(Long commentId) {
//        return String.format("comment-like:%d:count", commentId);
//    }
//
//    /**
//     * 获取mysql点赞状态
//     * @param commentLikesReq
//     * @return com.example.entity.CommentLike
//     */
//    private CommentLike getByCommentLikesReq(CommentLikesReq commentLikesReq) {
//        //获取登录用户的id
//        String userId = "";
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        if(authentication != null) {
//            userId = authentication.getPrincipal().toString();
//        }
//
//        if("".equals(userId)) {
//            throw new RuntimeException("没有登录用户信息，却访问了需要登录的接口");
//        }
//
//        //构建条件构造器
//        LambdaQueryWrapper<CommentLike> lambdaQueryWrapper = new LambdaQueryWrapper();
//        lambdaQueryWrapper
//                .eq(CommentLike::getUid, userId)
//                .eq(CommentLike::getCommentId, commentLikesReq.getCommentId());
//
//        CommentLike commentLike = getOne(lambdaQueryWrapper);
//        return commentLike;
//    }
}
